<?
/*

	Various blog functions
	
*/


	// check for install
	$install_completed=1;
	if (!file_exists($blogRoot."txts") || !file_exists($blogRoot."settings")) {
		$install_completed=0;
	}
	
	

	// Read our config settings
	readFullConfig();
	



	// new password specified?
	if (isset($_POST['savenpass'])) {
		writeConfigSetting("password",md5($_POST["npassword"]));
		$password=md5($_POST['newpassword']);
	}
	



	// Handle and check for login 
	session_start();

	$loggedIn=false;
	if ($_SESSION['auth'] OR $_COOKIE["login"]==$password) {
		if (Time()<$_SESSION['auth']['time'] OR $_COOKIE["login"]==$password) {
			$_SESSION['auth']['time']=Time()+3600;
		} else {
			Session_Destroy();
			// login time expired
			Header('Location: ?menu=login&err=1');
		}
	}



	
		
	// Status update / message posted?
	if ($_POST["submit"]==$lang["menu_login"]) {
		if (md5($_POST["password"])==$password) {
			if($_POST["permanent"]=="1") {
				$login=$password;
				setcookie("login", $login, time()+(60*60*24*365));
			}
			$_SESSION['auth'] = Array (
				'time' => Time()+3600,
			);
			// if logged
			//Header('Location: ?' . SID);
		} else {
			Header('Location: ?menu=login&err=2');
		}
	}


	if ($_SESSION['auth']) $loggedIn=true;


	if ($loggedIn) {
		// Logout request?
		if ($_GET["menu"]=="logout"){
			Session_Destroy();
			setcookie("login", "", time()+(60*60*24*365));
			Header('Location: '.$blogRoot.'../');
		}
	}




	// load our service plugins
	$handle=opendir($blogRoot."api/"); 
	$retVal=null;
	$pluginServices=array();
	while ($file = readdir($handle)) { 
		if (substr($file,0,1)!="." && substr($file,0,1)!="_") {
			$fName = $blogRoot."api/$file";
			
			require_once($fName);

			$serviceName=substr($file,0,strpos($file,".php"));
			$pluginServices[$serviceName]=call_user_func($serviceName."_getType");
		}
	} 
	asort($pluginServices);


	// load our system plugins
	$handle=opendir($blogRoot."plugins/"); 
	$retVal=null;
	$plugins=array();
	while ($file = readdir($handle)) { 
		if (substr($file,0,1)!="." && substr($file,0,1)!="_") {
			$fName = $blogRoot."plugins/$file";
			
			require_once($fName);

			$shortName=substr($file,0,strpos($file,".php"));
			$plugins[$shortName]=call_user_func($shortName."_pluginType");
		}
	} 
	asort($pluginServices);


// *************** SYSTEM FUNCTIONS BELOW ***********************************//






/*
	Convert date to timestamp, and then it can be shown with the date() function
*/	
function getTimeStamp($datefromdb) {
	$datefromdb=str_replace("-","",$datefromdb);
	$datefromdb=str_replace(":","",$datefromdb);
	$year = substr($datefromdb,0,4);
	$mon  = substr($datefromdb,4,2);
	$day  = substr($datefromdb,6,2);
	
	$hour = substr($datefromdb,9,2);
	$min  = substr($datefromdb,11,2);
	$sec  = substr($datefromdb,13,2);
	
	return mktime($hour,$min,$sec,$mon,$day,$year);	
}



function serviceIcon($servicename) {
	global $blogRoot;
	if (file_exists($blogRoot."themes/_system/serviceicons/".$servicename.".png"))	return $blogRoot."themes/_system/serviceicons/".$servicename.".png";
	else return false;
}


/**
	Handle and/or display according to the action requested

		----- TODO: move this to a proper admin page
*/

function Actions() {
	global $lang;
	
	switch($_GET["menu"]) {
		// if login => show login form :)
		case "login":
			$text.='<div class="actions center">
							<form action="#" method="post">
								'.$lang["form_password"].': <input type="password" name="password" size="10">
								<input type="checkbox" name="permanent" value="1"><small>Permanent</small>&nbsp;&nbsp;<input type="submit" name="submit" value="'.$lang["menu_login"].'">
							</form>
						</div>';
		break;
		
		case "err":
			$text="Error!: ".$_GET["err"];
		break;


		/* If we are logged in, we display the post message box */
		default:
			if($_SESSION["auth"]) {
				/*
				$text.='<div class="message_postform">
								<form action="#" method="post">
									<textarea name="message" maxlength="150" value="'.$_POST["message"].'"></textarea>
									<br/>
									<span style="float:right;">
									<input type="submit" name="submit" value="'.$lang["submit_insert"].'">
									</span>
								</form>
							</div>';
			*/							
			}
		break;
		
	}
	return $text;
}





	

/**
	Generate the dynamic sidebar, using plugin widgets
*/
	function drawSideBar() {
		global $blogRoot;
		$configFile = $blogRoot."settings/sidebar.txt";
		// file exists?
		if (!file_exists($configFile)) return;


		// read contents
		clearstatcache();
		$open3 = fopen($configFile, "rb");
			if(filesize($configFile)!="0") $contents = fread($open3, filesize($configFile));
		fclose($open3);
		
		// display services
		if (strpos($contents,"\r\n")) $entrylist=explode("\r\n",$contents);
		else $entrylist=explode("\n",$contents);
		
		foreach ($entrylist as $item) {
			if (trim($item)!="") {
				$entry=explode("|",$item);
				
				if ($entry[2]!="") print "<h2>".$entry[2]."</h2>";
				if (function_exists($entry[1]."_draw")) call_user_func($entry[1]."_draw",$entry[3]);
			}
		}
		
	}


/**
	Draw the login/admin/about/stuff menu 
	
*/
	function drawMenu() {
		global $lang,$blogRoot,$blogtitle,$loggedIn;
	?>
		<div id="menubar">
			<?
				//print "<span style='float:left;'>Puddle: <a href='".$blogRoot."../'>".$blogtitle."</span>";
				
				if ($loggedIn) print " <a href='".$blogRoot."../?menu=logout'><img src='".$blogRoot."themes/_system/imgs/icon_logoff.png' title='log out'></a>";
				 
				 print " <a href='".$blogRoot."../?'><img src='".$blogRoot."themes/_system/imgs/icon_home.png' title='home'></a>";
				 print " <a href='".$blogRoot."admin.php'><img src='".$blogRoot."themes/_system/imgs/icon_admin.png' title='admin'></a>";
				 print " <a href='".$blogRoot."../?about=1'><img src='".$blogRoot."themes/_system/imgs/icon_about.png' title='about'></a>";
			?>
		</div>
	<?
	}
	



function drawTweet($line) {
	global $lang,$disqusname,$enableComments,$loggedIn,$blogRoot;
	$entry=explode("|",$line);
	

		$serviceInfo=$entry[1];
		// filter out any settings
		if (!is_numeric($serviceInfo)) {
			$servicesettings=explode(":",$serviceInfo);
			$serviceInfo=$servicesettings[0];
			
			foreach($servicesettings as $setting) {
				if ($setting=="h") return;	// hidden, no show!
			}
		}

		$myService=$entry[2];

		// load date
		$date = substr($entry[0],0,10);

		$itemDate="";
		$explodeDate=explode(".",$date);
							
		// day
		if(substr($explodeDate[0],0,1)=="0") {
			$itemDate.=substr($explodeDate[0],1,2);
		} else {
			$itemDate.=$explodeDate[0];
		}
		
		// month
			$itemDate.=$lang["months"][str_replace("0","",$explodeDate[1])];
		// and year
			$itemDate.=' '.$explodeDate[2];
				$date = explode(".",$date);
				$time= substr($entry[0],11,8);
				// explode time for unixtime
				$time = explode(":",$time);
				// create unixtime
				$unixtime = mktime($time[0], $time[1], $time[2], $date[1], $date[0], $date[2]);
				
				
				// check on timestamp time value, and beautify it
				$date=strtotime($entry[0]);
				$timeline="";
				if (date("Ymd",time())==date("Ymd",$date)) {
					// it's today, so make the time nicer
					if (date("H",time())==date("H",$date)) {
						$minAgo=date("i",time())-date("i",$date);
						$itemDate=$minAgo." minutes ago";
					} else {
						$itemDate="Today @ ".date("Y.m.d H:i",$date); //date("H:i",$entry[0]);
					}
				} else if (date("Ymd",time())==date("Ymd",$date)-1) {
					$itemDate="Yesterday @ ".date("H:i",$date);
				} else {
					$itemDate.=" @ ".date("H:i",$date);
				}
				
			
			if (function_exists($myService."_getAction")) $itemAction=call_user_func($myService."_getAction",$line);
			else $itemAction=null;
			$itemCaption=call_user_func($myService."_getCaption",$line);
			$itemPost=call_user_func($myService."_getPost",$line);
			$itemLink=call_user_func($myService."_getLink",$line);
			$itemCommentLink='<a href="?cmt='.$unixtime.'#disqus_thread">Comments (View)</a>';
			if ($loggedIn && $myService=='puddle') $itemCommentLink.=" | <a href='".$blogRoot."admin.php?page=puddle&edit=".$unixtime."'>Edit</a>";
			

			if (function_exists("theme_drawTweet")) {
				$returnComment.=call_user_func("theme_drawTweet",
							$itemAction,	// description of "I liked" or "I posted"
							$itemCaption,	// Caption of item, can be empty
							$itemPost,		// content of item, can be empty
							$itemLink,		// link to the item
							$itemCommentLink,	// link to adding/viewing comments of this post
							$itemDate,
							$myService,
							strtotime($entry[0]));	// formatted date of item
			} else {
				$text="<div id='tweet'>";

				if ($itemAction) $text.="<h3>".$itemAction."</h3>";
					
				if ($itemCaption) {
					$text.="<h1>";
					if ($itemLink) $text.="<a href='".$itemLink."'>";
					$text.=$itemCaption;
					if ($itemLink) $text.="</a>";
					$text.="</h1>";
				}else $text.=$itemPost;

				$text.=' <span class="subline">'.$itemDate.' - ';
				$text.=$time[0].':'.$time[1];
					
				// comment's link
				if ($disqusname) $text.=$itemCommentLink;
					
				if ($itemLink) $text.=" | <a href='".$itemLink."'>&#187; link</a>";
				$text.="</span><br/><br/>";

				if ($itemCaption) $text.=$itemPost;
				$text.="</div><div id='clearit'> </div>";
				
				$returnComment.=$text;
			}
					
		return $returnComment;

}


/**
	Draw the specified tweet
*/
function loadTweet($tweetID) {
		global $blogRoot,$lang,$maxpostsperpage,$pluginServices, $tweetfile;
		$returnComment="";
		$text="";
		
		$itemdate=date("YmdHis",$tweetID);
		
		$myfile=$blogRoot."txts/".date("Y",$tweetID).".".date("m",$tweetID).".txt";
		
		clearstatcache();
		if((file_exists($myfile)) && filesize($myfile)!="0") {
				
				// load archive
				$load = @file($myfile);

				// load lines
				while(count($load)) {
					$line=array_shift($load);
					$info=explode("|",$line);
					if (date("YmdHis",strtotime($info[0]))==$itemdate) {
						return drawTweet($line);
					}
				}
					
		}
}





/**
	The nitty-gritty function, it loads our tweets-log and displays the items
*/
function loadTweets($page,$archivefile=null) {
		global $blogRoot,$lang,$maxpostsperpage,$pluginServices, $tweetfile,$lang;
		$returnComment="";
		$text="";
		
		if (!file_exists($blogRoot."settings") || !file_exists($blogRoot."txts")) {
			$returnComment="<div id='tweet'><h1>Welcome to Puddle!</h1>";
			
			$returnComment.="<p>This it your own little puddle blog.<br/>";
			$returnComment.="Go to your <a href='".$blogRoot."admin.php'>Admin</a> page.<br/>";
			$returnComment.="Login with the default password: <strong>puddle</strong>.</p>";
			$returnComment.="</div>";
			
			return $returnComment;
		} 
		

		clearstatcache();
		
		$pagey=date("Y",time());
		$pagem=date("m",time());
		
		$pageCount=1;
		$postCount=0;
		
		if ($archivefile) {
			$myfile=$blogRoot."txts/".$archivefile.".txt";
			$maxpostsperpage=500; // should effectivly display everything of the archive
			$page=1;
			
			$archivetitle=$lang["months"][str_replace("0","",substr($archivefile,5,2))]." ".substr($archivefile,0,4);
	
			print "<p><small><strong>Archive:</strong> ".$archivetitle.", ";
			print "<a href='".$blogRoot."../#'>click here</a> to remove archive filter.</small></p>";
			
		} else $myfile=$blogRoot."txts/".$pagey.".".$pagem.".txt";
		
		$fileNotFound=0;

		if (isset($_POST['keywords'])) {
			$keywords=$_POST['keywords'];
			print "<p><small><strong>Keywords:</strong> ".$keywords.", ";
			print "<a href='".$blogRoot."../#'>click here</a> to remove keyword filter.</small></p>";
		}
		
		if (isset($_GET['service'])) {
			$service=$_GET['service'];
			print "<p><small><strong>Service:</strong> ".$service.", ";
			print "<a href='".$blogRoot."../#'>click here</a> to remove service filter.</small></p>";
		}
		
		while ($postCount<$maxpostsperpage) {
			
			// file exists and have zero size?
			if((file_exists($myfile)) && filesize($myfile)!="0") {
				// load archive
				$load = @file($myfile);
		
				// load lines
				while(count($load)>0 && $postCount<$maxpostsperpage) {
					$line=array_shift($load);
					$items=explode("|",$line);

					if ($pageCount==$page) {
						if ($keywords) {
							$word=explode(" ",$keywords);
							$include=false;
							foreach($word as $value) {
								if (stristr($line,$value)) $include=true;
							}
						} else if ($service) {
							if ($items[2]==$service) $include=true;
							else $include=false;
						} else $include=true;
					
						if ($include) $returnComment.=drawTweet($line);
						else $postCount--;
					}
					$postCount++;

					if ($postCount==$maxpostsperpage) {
						if ($pageCount<$page) {
							$postCount=0;
							$pageCount++;
						}
					}
				}

			} else {
				$fileNotFound++;
				if ($fileNotFound>5) break;
			}
			
			if ($archivefile) return $returnComment;
			
			$pagem--;
			if ($pagem<1) {
				$pagem=12;
				$pagey--;
			}
			if (strlen($pagem)<2) $pagem="0".$pagem;
			$myfile=$blogRoot."txts/".$pagey.".".$pagem.".txt";
			
		}


		// previous page? with newer items
		if ($page>1) {
			$returnComment.="<a href='".$blogRoot."../?page=".($page-1)."'>Newer</a>";
		}
		
		// older pages? with older items
		if (count($load)>0 || ((file_exists($myfile)) && filesize($myfile)!="0") ) {
			$returnComment.=" <a href='".$blogRoot."../?page=".($page+1)."'>Older</a>";
		}
		
		
		// anything written?
		if ($postCount==0) {
			$returnComment="<h1>Bummer!</h1>There don't seem to be any posts available";
		}
		


		return $returnComment;
}




/**
	Post a new tweet to the blog 
	
*/
function addTweet() {
	global $lang,$blogRoot;

	if(!($_SESSION["auth"])) { Header('Location: ?err=8'); die; }
	
	$tweetfile=$blogRoot."txts/".date("Y",time()).".".date("m",time()).".txt";


	// format message
	
		$message=str_replace(">","&gt;",$_POST["message"]);
		$message=str_replace("<","&lt;",$message);
		$message=str_replace('"','&#34;',$message);
		$message=str_replace(CHR(13),'',$message);
		$message=str_replace(CHR(10),'',$message);
		$message=str_replace('|',':',$message);

	// format caption
		$caption=str_replace(">","&gt;",$_POST["caption"]);
		$caption=str_replace("<","&lt;",$caption);
		$caption=str_replace('"','&#34;',$caption);
		$caption=str_replace(CHR(13),'',$caption);
		$caption=str_replace(CHR(10),'',$caption);
		$caption=str_replace('|',':',$caption);
	

	// EDIT MODE? if ID is set we edit!
	if (isset($_POST['id'])) {
		
		$tweetID=$_POST['id'];
		$itemdate=date("YmdHis",$tweetID);
		$tweefile=$blogRoot."txts/".date("Y",$tweetID).".".date("m",$tweetID).".txt";
		
		// find tweet and replace tweet
		// load archive
		
		$load = @file($tweetfile);

		// load lines
		$open=fopen($tweefile,"w");
		$first=true;
		while(count($load)) {
			$line=array_shift($load);
			$line=str_replace(CHR(13),'',$line);
			$line=str_replace(CHR(10),'',$line);
			
			$info=explode("|",$line);

			if (date("YmdHis",strtotime($info[0]))==$itemdate) {
				$info[3]=$caption;
				$info[5]=$message;
			}
			$line=implode("|",$info);

			if (!$first) fwrite($open,"\r\n");
			fwrite($open,$line);
			$first=false;
		}
		fclose($open);
	}
	
	
	
	// no edit, so add new post to the blog
	// file exists?
	if (!isset($_POST['id'])) {
			if(file_exists($tweetfile)) {
				if(!(is_writable($tweetfile))) Header('Location: ?err=4');
			} else {
				// create the file :)
				$create = touch($tweetfile);
				chmod($tweetfile,0777);
				if(!($create)) Header('Location: ?err=9');
			}

			$open3 = fopen($tweetfile, "r");
			if(filesize($tweetfile)!="0") {
				$contents = fread($open3, filesize($tweetfile));
			}
			fclose($open3);
			
			
			// load file :)
			$open = fopen($tweetfile, "w+");
			
				$today = Date("d.m.Y");
				$hour = Date("H:i:s");
				$service = "puddle";
				
				$string = $today." ".$hour."|0|".$service."|".$caption;

				$date = explode(".",$today);
				$time = explode(":",$hour);
				$guid = mktime($time[0], $time[1], $time[2], $date[1], $date[0], $date[2]);
				$string .="|".$guid."|".$message."\r\n";

				// write new posts
				fwrite($open,$string);
				// write the original content below it
				fwrite($open,$contents);

			fclose($open);
	}
}




/**
	Hide or unhide a tweet
	
*/
function hideTweet($tweetID,$hide) {
	global $lang,$blogRoot;

		$itemdate=date("YmdHis",$tweetID);
		$tweetfile=$blogRoot."txts/".date("Y",$tweetID).".".date("m",$tweetID).".txt";
		
		
		//return;
		// find tweet and replace tweet
		// load archive
		
		$load = @file($tweetfile);

		// load lines
		$open=fopen($tweetfile,"w");
		$first=true;
		while(count($load)) {
			$line=array_shift($load);
			$line=str_replace(CHR(13),'',$line);
			$line=str_replace(CHR(10),'',$line);
			
			$info=explode("|",$line);
			
			if (date("YmdHis",strtotime($info[0]))==$itemdate) {
				$info[1]=str_replace(":h","",$info[1]);

				if ($hide) {
					$info[1].=":h";
				}
			}

			$line=implode("|",$info);
			
			//print $info[1]."<Br/>";

			if (!$first) fwrite($open,"\r\n");
			fwrite($open,$line);
			$first=false;
		}
		fclose($open);
}








/**
	Post a new tweet to the blog
	
*/
function insertEntries($newitems,$service,$serviceID) {
	global $lang,$blogRoot,$silentmode;
	

		//if(!($_SESSION["auth"])) { Header('Location: ?err=8 - '.$_SESSION["auth"]); die; }
		
		if (count($newitems)==0) return;
		
		// generate correct entry lines for the output
		foreach ($newitems as $item) {
			//$item->post=htmlspecialchars($item->post);
			//$item->post=nl2br($item->post);
			$item->post=str_replace(CHR(13),'<br/>',$item->post);
			$item->post=str_replace(CHR(10),'',$item->post);
			$item->post=str_replace('|',':',$item->post);

			$item->link=str_replace(CHR(13),'<br/>',$item->link);
			$item->link=str_replace(CHR(10),'',$item->link);

			$item->guid=str_replace(CHR(13),'<br/>',$item->guid);
			$item->guid=str_replace(CHR(10),'',$item->guid);

			$item->extra=str_replace(CHR(13),'<br/>',$item->extra);
			$item->extra=str_replace(CHR(10),'',$item->extra);

	
			$datestamp=strtotime($item->pubDate);
			$today = Date("d.m.Y",$datestamp);
			$hour = Date("H:i:s",$datestamp);

			$entry = $today." ".$hour."|".$serviceID."|".$service."|".$item->post;

			$date = explode(".",$today);
			$time = explode(":",$hour);
		
			if (!$item->guid) $item->guid = mktime($time[0], $time[1], $time[2], $date[1], $date[0], $date[2]);
			$entry .="|".$item->guid;
			if ($item->extra) $entry.=$item->extra;
			$item->entryline=$entry;
		}
		
		$importCount=count($newitems);
		
		// now we read the existing entries or the correct archive into an array
		$path=$blogRoot."txts/tweets.txt";
		
		// file exists?
		if(file_exists($path)) {
			if(!(is_writable($path))) Header('Location: ?err=4');
		} else {
			// create the file :)
			$create = touch($path);
			chmod($path,0777);
			if(!($create)) {
				print "error creating archive:".$path."<br/>";
				die();
			}
		}


		// read contents
		clearstatcache();
		$open3 = fopen($path, "rb");
			if(filesize($path)!="0") $contents = fread($open3, filesize($path));
		fclose($open3);

		// fetch all entries
		if (strpos($contents,"\r\n")) $entrylist=explode("\r\n",$contents);
		else $entrylist=explode("\n",$contents);
		
		// process the list, and insert into our new array (unless the guid is duplicate!)
		foreach ($entrylist as $item) {
			$entry=explode("|",$item);
			if (!in_array($entry[3],$newitems)) {
				$indx=date("YmdHis",strtotime(trim($entry[0])));
				$newitems[$indx]->entryline=$item;
			} else {
				$importCount--;	// 1 less to import
			}
		}
		
		krsort($newitems);
		

		// write new file
		$open = fopen($path, "w");
		$first=true;
		foreach ($newitems as $key=>$item) {
			if (!$first) fwrite($open,"\r\n");
			fwrite($open,$item->entryline);
			$first=false;
		}
		fclose($open);

		if (!$silentmode) {
			print "<img src='".serviceIcon($service)."'>";
			print " Imported ".$importCount." items.<br/>";
		}
}


// check if this is a new item / guid
function newGuid($guid) {
	global $blogRoot;
	$guidFound=false;
	
	// read contents
	/*
	$path = $blogRoot."txts/tweets.txt";
	clearstatcache();
	$open3 = fopen($path, "rb");
		if(filesize($path)!="0") $contents = fread($open3, filesize($path));
	fclose($open3);
*/

		clearstatcache();
		$handle=opendir($blogRoot."txts/"); 
		$totalTweets=0;

		// process all archive files, skipping the current tweets list
		while ($file = readdir($handle)) { 
			if (substr($file,0,1)!="." && substr($file,0,1)!="_" && (filesize($blogRoot."txts/".$file)!="0")) {
				
				$file=$blogRoot."txts/".$file;
				
				$open3=fopen($file,"rb");
					$contents = fread($open3, filesize($file));
				fclose($open3);
				
				if (strpos($contents,$guid)>0) $guidFound=true;
			}
		}
	
	return !$guidFound;
}



// Write the specified setting into the config.txt file
function writeConfigSetting($cfgsetting,$cfgvalue) {
		global $blogRoot;
		$configfile=$blogRoot."settings/config.txt";
	
	// file exists?
		if(file_exists($configfile)) {
			if(!(is_writable($configfile))) {
				print "The config.txt file is not writeable... :(";
			}
		} else {
			$create = touch($configfile);
			if(!($create)) {
				print "The config.txt file could not be created... :(";
			} else {
				print "created config file.. :)";
			}
			chmod($configfile,0777);
		}

		clearstatcache();
		$open3 = fopen($configfile, "rb");
		if(filesize($configfile)!="0") {
			$contents = fread($open3, filesize($configfile));
		}
		fclose($open3);
		
		if (strpos($contents,"\r\n")) $entrylist=explode("\r\n",$contents);
		else $entrylist=explode("\n",$contents);
		
		$open3 = fopen($configfile, "w");
		
		$settingSaved=false;
		$first=true;
		
		foreach ($entrylist as $entry) {
			if (trim($entry)!="") {
				$item=explode("|",$entry);
				if ($item[0]==$cfgsetting) {
					$item[1]=$cfgvalue;
					$settingSaved=true;
				}
				if (!$first) fwrite($open3,"\r\n");
				
				fwrite($open3,$item[0]."|".$item[1]);
				$first=false;
			}
		}
		
		if (!$settingSaved) {
			if (!$first) fwrite($open3,"\r\n");
			fwrite($open3,$cfgsetting."|".$cfgvalue);
		}
		
		fclose($open3);
		
	
}



// Read the specified config value
function readConfigSetting($cfgsetting) {
		global $blogRoot;
		$configfile=$blogRoot."settings/config.txt";
	
	// file exists?
		if(!file_exists($configfile)) return null;
		
		clearstatcache();
		$open3 = fopen($configfile, "rb");
		if(filesize($configfile)!="0") {
			$contents = fread($open3, filesize($configfile));
		}
		fclose($open3);
		
		if (strpos($contents,"\r\n")) $entrylist=explode("\r\n",$contents);
		else $entrylist=explode("\n",$contents);
		
		$cfgvalue=null;
		foreach ($entrylist as $entry) {
			if (trim($entry)!="") {
				$item=explode("|",$entry);
				
				if ($item[0]==$cfgsetting) {
					return $item[1];
				}
			}
		}
	
}


	/**
		Read all the config settings required to run the system
		
	*/

	function readFullConfig() {
		global $blogname,$blogtitle,$disqusname,$maxpostsperpage,
				$showmenu,$enablecomments,$includeATtweets,$password,
				$tweetfile,$blogRoot,$theme,$profileimg;
				
		$blogname=readConfigSetting("blogname");
		$blogtitle=readConfigSetting("blogtitle");
		$disqusname=readConfigSetting("disqusname");
		$maxpostsperpage=readConfigSetting("maxpostsperpage");

		$showmenu=readConfigSetting("showmenu");
		if ($showmenu==null) $showmenu=1;
		$enableComments=readConfigSetting("enableComments");
		
		if ($disqusname==null) $enableComments=0;
		else $enableComments=1;
		
		$includeATtweets =readConfigSetting("includeATtweets");
		$theme=readConfigSetting("theme");
		if ($theme=="" or $theme==null) $theme="puddlelight";
		
		$password=readConfigSetting("password");
		if ($password==null) $password=md5('puddle');
		
		$profileimg=readConfigSetting("profileimg");
		

		$tweetfile=$blogRoot."txts/".date("Y",time()).".".date("m",time()).".txt";
	}



	/**
		Walk thru the tweets.txt file and archive all older items into year.month.txt files
	*/
	function archiveTweets() {
		global $tweetfile,$blogRoot;

		// file exists and have zero size?
		clearstatcache();
		$myfile=$blogRoot."txts/tweets.txt";
		if(!(file_exists($myfile)) OR filesize($myfile)=="0") {
			return $text;
		}

		
		$open3=fopen($myfile,"rb");
		$contents = fread($open3, filesize($myfile));
		fclose($open3);
		
		if (strpos($contents,"\r\n")) $entrylist=explode("\r\n",$contents);
		else $entrylist=explode("\n",$contents);


		unlink($myfile);
		
		// process all entries in current tweetlist, and archive them.
		foreach($entrylist as $entry) {
			$items=explode("|",$entry);
			if (trim($entry)!="") {
				// get name of new archive file
				$date=substr($items[0],0,10);
				$archive=$blogRoot."txts/".substr($date,6,4).".".substr($date,3,2).".txt";
				
				// if archive is new, we create it
				if (!file_exists($archive)) {
					$create = touch($archive);
					chmod($archive,0777);
					if(!($create)) {
						print "Error creating archive:".$archive."<br/>";
						return false;
					}
				}
				
				// fetch all entries from the archive
				clearstatcache();
				$argcontents=null;
				$open1=fopen($archive,"rb");
				if (filesize($archive)!="0") {
						$argcontents=fread($open1, filesize($archive));
				}
				fclose($open1);

				if (strpos($argcontents,"\r\n")) $argentrylist=explode("\r\n",$argcontents);
				else $argentrylist=explode("\n",$argcontents);
				
				$duplicate=false;
				$first=true;
				$newitems=null;
				foreach($argentrylist as $argentry) {
					if (trim($argentry)!="") {
						$argitem=explode("|",$argentry);
						
						if ($argitem[4]==$items[4]) $duplicate=true;

						$indx=date("YmdHis",strtotime(trim($argitem[0])));
						$newitems[$indx]->entryline=$argentry;
					}
				}

				if (!$duplicate) {
					$indx=date("YmdHis",strtotime(trim($items[0])));
					$newitems[$indx]->entryline=$entry;
				}

				krsort($newitems);

				// write new file
				$open = fopen($archive, "w");
				$first=true;
				foreach ($newitems as $key=>$item) {
					if (!$first) fwrite($open,"\r\n");
					fwrite($open,$item->entryline);
					$first=false;
				}
				fclose($open);

			}
		}
	}
	
	/**
		Count amount of tweets
	*/
	function countTweets() {
		global $tweetfile,$blogRoot;

		clearstatcache();
		$handle=opendir($blogRoot."txts/"); 
		$totalTweets=0;

		// process all archive files, skipping the current tweets list
		while ($file = readdir($handle)) { 
			if (substr($file,0,1)!="." && substr($file,0,1)!="_" && (filesize($blogRoot."txts/".$file)!="0") && substr($file,0,6)!="tweets") {
				
				$file=$blogRoot."txts/".$file;
				
				$open3=fopen($file,"rb");
				$contents = fread($open3, filesize($file));
				fclose($open3);
				
				if (strpos($contents,"\r\n")) $entrylist=explode("\r\n",$contents);
				else $entrylist=explode("\n",$contents);

				$totalTweets+=count($entrylist);
			}
		}
		

		return $totalTweets;
		
	}

?>
